package com.captjack.rest.filter;

import com.captjack.rest.configuration.security.TokenAuthenticationManager;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器
 *
 * @author Jack Sparrow
 * @version 1.0.0
 * @date 2018/6/3 22:50
 * package com.captjack.rest.filter
 */
@Component
public class LoginTokenFilter extends OncePerRequestFilter {

    /**
     * token管理
     */
    private final TokenAuthenticationManager tokenAuthenticationManager;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            // 鉴权
            Authentication authentication = tokenAuthenticationManager.getAuthentication(request);
            // 授权
            SecurityContextHolder.getContext().setAuthentication(authentication);
            // 执行其他过滤器
            filterChain.doFilter(request, response);
        } catch (JwtException e) {
            // 可以在这里指定重定向还是返回错误接口示例
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
    }

    @Autowired
    public LoginTokenFilter(TokenAuthenticationManager tokenAuthenticationManager) {
        this.tokenAuthenticationManager = tokenAuthenticationManager;
    }

}
